package com.example.demo.service;


import com.example.demo.mapper.StudentMapper;
import com.example.demo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    // 获取所有学生
    public List<Student> findAllStudents() {
        return studentMapper.findAll();
    }

    // 根据学号查找学生
    public Optional<Student> findStudentById(String studentId) {
        return studentMapper.findById(studentId);
    }

    // 根据班级查找学生
    public List<Student> findStudentsByClassName(String className) {
        return studentMapper.findByClassName(className);
    }

    // 注册/创建学生
    public Student createStudent(Student student) {
        // 1. 业务校验
        if (student.getStudentId() == null || student.getPassword() == null) {
            throw new IllegalArgumentException("学号和密码不能为空。");
        }

        // 2. 检查学号是否已存在
        if (studentMapper.findById(student.getStudentId()).isPresent()) {
            throw new IllegalStateException("学号已存在，注册失败。");
        }

        // 3. 实际应用中：在这里对 student.getPassword() 进行加密（如使用 BCryptPasswordEncoder）
        // student.setPassword(passwordEncoder.encode(student.getPassword()));

        if (studentMapper.insert(student) > 0) {
            return student;
        } else {
            throw new RuntimeException("学生信息创建失败。");
        }
    }

    // 更新学生信息
    public boolean updateStudent(Student student) {
        // 确保要更新的学生存在
        if (student.getStudentId() == null || studentMapper.findById(student.getStudentId()).isEmpty()) {
            return false;
        }

        // 实际应用中：如果更新了密码，需要对新密码进行加密

        return studentMapper.update(student) > 0;
    }

    // 删除学生
    public boolean deleteStudent(String studentId) {
        return studentMapper.deleteById(studentId) > 0;
    }
}